//
//  LeaseListViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/1/19.
//  Copyright © 2019 xiaohan. All rights reserved.
//



#import "LeaseListViewController.h"
#import "EOSService.h"
#import "EOSAccountResult.h"
#import "TheRedemptionViewController.h"
#import "TheRedemptionPreviewViewController.h"
@implementation LeaseListCell

- (void)setupUI{
    self.selectionStyle = UITableViewCellSelectionStyleDefault;
    self.selectedBackgroundView = [UIView new];
    self.backView = [UIView new];
    self.backView.backgroundColor = UIColor.whiteColor;
    [self.backView.layer setLayerShadow:kShadowColor offset:CGSizeMake(0, 0) radius:6];
    self.backView.layer.cornerRadius = AdaptedWidth(10);
    [self.contentView addSubview:self.backView];
    
    self.nameLab = [UILabel new];
    self.nameLab.textColor = UIColorHex(#FFAE00);
    self.nameLab.font = kDefaultFont(15);
    [self.backView addSubview:self.nameLab];
    
    self.copBtn = [UIButton new];
    [self.copBtn setImage:IMAGE_NAMED(@"yellow_copy") forState:UIControlStateNormal];
    [self.backView addSubview:self.copBtn];
    kWeakSelf(self);
    [self.copBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [PhoneTool copyStr:weakself.nameLab.text];
    }];
    
    self.cpuLab = [UILabel new];
    self.cpuLab.textColor = UIColorHex(#333333);
    self.cpuLab.font = kDefaultFont(13);
    [self.backView addSubview:self.cpuLab];
    self.netLab = [UILabel new];
    self.netLab.textColor = UIColorHex(#333333);
    self.netLab.font = kDefaultFont(13);
    [self.backView addSubview:self.netLab];
    
    [self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(AdaptedWidth(15));
        make.right.mas_equalTo(AdaptedWidth(-15));
        make.top.mas_equalTo(AdaptedWidth(10));
        make.bottom.mas_equalTo(AdaptedWidth(-10));
    }];
    [self.nameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(kNormalSpace);
    }];
    [self.self.copBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.equalTo(self.nameLab.mas_right).offset(3);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    [self.cpuLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(AdaptedWidth(15));
        make.right.mas_equalTo(AdaptedWidth(-22));
    }];
    [self.netLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(AdaptedWidth(-22));
        make.bottom.mas_equalTo(AdaptedWidth(-15));
    }];

}

//处理选中背景色问题
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    if (!self.editing) {
        return;
    }
    [super setSelected:selected animated:animated];
    if (self.editing) {
        self.backView.backgroundColor = [UIColor whiteColor];
        self.contentView.backgroundColor = [UIColor clearColor];
        self.backgroundColor = [UIColor clearColor];
        self.nameLab.backgroundColor = [UIColor whiteColor];
        self.cpuLab.backgroundColor = [UIColor whiteColor];
        self.netLab.backgroundColor = [UIColor whiteColor];
    }
}

-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
//    self.backView.backgroundColor = [UIColor whiteColor];
//    self.contentView.backgroundColor = [UIColor clearColor];
//    self.backgroundColor = [UIColor clearColor];
    return;
}

@end

@interface BottomView : UIView

/**
 全选按钮
 */
@property (nonatomic ,strong) UIButton *allBtn;
/**
 删除按钮
 */
@property (nonatomic ,strong) UIButton *deleteBtn;

@end
@implementation BottomView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.allBtn];
        [self addSubview:self.deleteBtn];
    }
    return self;
}

- (UIButton *)allBtn{
    if (!_allBtn) {
        self.allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _allBtn.frame = CGRectMake(10, 0, 60, 49);
        _allBtn.titleLabel.font = kBoldFont(15);
        [_allBtn setTitle:XLocalized(@"全选") forState:UIControlStateNormal];
        [_allBtn setTitle:XLocalized(@"取消全选") forState:UIControlStateSelected];
        [_allBtn setTitleColor:UIColorHex(333333) forState:UIControlStateNormal];
    }
    return _allBtn;
}

- (UIButton *)deleteBtn{
    if (!_deleteBtn) {
        self.deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteBtn.frame = CGRectMake(self.bounds.size.width - 70, 0, 60, 49);
        _deleteBtn.titleLabel.font = kBoldFont(15);
        [_deleteBtn setTitle:XLocalized(@"赎回") forState:UIControlStateNormal];
        [_deleteBtn setTitleColor:UIColorHex(333333) forState:UIControlStateNormal];
        [_deleteBtn setTitleColor:UIColorHex(999999) forState:UIControlStateDisabled];
    }
    return _deleteBtn;
}

@end
@interface LeaseListViewController ()
@property (nonatomic,strong) BottomView *bottomView;
@property (nonatomic,assign) BOOL allChoose;
@property (nonatomic,strong) EOSService *eosService;
@property (nonatomic,strong) NSMutableArray <EOSAccountDelegatedBandwidth*>*list;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) NSMutableArray *chooseArr;
@property (nonatomic,weak) UIButton* rightBtn;

@end

@implementation LeaseListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self.tableView.mj_header beginRefreshing];
}
- (void)loadMore:(BOOL)isMore{
    if (self.tableView.isEditing) {
        [self rightBtnClick:self.rightBtn];
    }
    NSInteger page = isMore ? (self.page + 1) : 1;
    [self.eosService getTableRowsParme:@{@"json":@(true),@"code":kContractName_EOSIO,@"scope":VALIDATE_STRING(self.wallet.wallet_name),@"table":@"delband",@"limit":@(page*100),@"lower_bound":@(0),@"uppper_bound":@(-1)} complete:^(BOOL success, NSString * _Nonnull errorMsg, id  _Nonnull data) {
        [self endHeaderFooterRefreshingIsHaveNextPage:[data[@"more"] integerValue]==1];
        if (success) {
            self.page = page;
            if (!isMore) {
                [self.list removeAllObjects];
            }
            NSArray*rows = data[@"rows"];
            if (ValidArray(rows)) {
                [rows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    EOSAccountDelegatedBandwidth *delegate = [EOSAccountDelegatedBandwidth modelWithJSON:obj];
                    if (![delegate.to isEqualToString:self.wallet.wallet_name]) {
                        [self.list addObject:delegate];
                    }
                }];
            }
            [self.tableView reloadData];
        }
    }];
}
///赎回
- (void)deleteData{
    NSMutableArray *data = [NSMutableArray array];
    for (NSIndexPath *indexPath in self.chooseArr) {
        [data addObject:[self.list objectAtIndex:indexPath.row]];
    }
    kWeakSelf(self);
    [TheRedemptionPreviewViewController alertController:self infoDelegate:data withWallet:self.wallet sureBlock:^(BOOL success) {
        [weakself loadMore:NO];
    }];
}
///全选
- (void)tapAllBtn:(UIButton*)allBtn{
    allBtn.selected = !allBtn.selected;
    [self.chooseArr removeAllObjects];
    if (allBtn.selected) {
        for (int i = 0; i< self.list.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [self.chooseArr addObject:indexPath];
        [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
    }else{
        for (int i = 0; i< self.list.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
        }
    }
    self.bottomView.deleteBtn.enabled =self.chooseArr.count;
}

- (void)rightBtnClick:(UIButton*)btn{
    if (btn) {
        _rightBtn = btn;
    }
    [_rightBtn setTitle:self.tableView.isEditing?XLocalized(@"多选"):XLocalized(@"取消") forState:UIControlStateNormal];
    if (self.tableView.isEditing) {
        [self.chooseArr removeAllObjects];
        self.bottomView.allBtn.selected = NO;
        self.bottomView.deleteBtn.enabled = NO;
        [self.tableView setEditing:NO animated:YES];
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.bottomView.top = self.view.bottom;
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.bottomView.mas_top);
                [self.view layoutIfNeeded];
            }];
        } completion:nil];
    }else{
        [self.tableView setEditing:YES animated:YES];
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.bottomView.top = self.view.bottom-self.bottomView.height;
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.bottomView.mas_top);
                [self.view layoutIfNeeded];
            }];
        } completion:nil];
    }
}
- (void)viewWillLayoutSubviews{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.customNavigationBar.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
}
- (void)setupUI{
    self.title = XLocalized(@"租借列表");
    self.tableView.rowHeight = AdaptedWidth(90);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addNavigationItemWithTitles:@[XLocalized(@"多选")] isLeft:NO target:self action:@selector(rightBtnClick:) tags:nil];
    [self.view addSubview:self.bottomView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.list.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LeaseListCell *cell = [LeaseListCell cellForTableView:tableView];
    EOSAccountDelegatedBandwidth *model = [self.list objectOrNilAtIndex:indexPath.row];
    cell.nameLab.text = model.to;
    cell.cpuLab.text = [NSString stringWithFormat:@"%@:%@",XLocalized(@"计算"),model.cpu_weight];
    cell.netLab.text = [NSString stringWithFormat:@"%@:%@",XLocalized(@"网络"),model.net_weight];
    return cell;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.editing) {
        [self.chooseArr addObject:indexPath];
        self.bottomView.allBtn.selected = self.chooseArr.count==self.list.count;
        self.bottomView.deleteBtn.enabled = self.chooseArr.count;
        return;
    }
    EOSAccountDelegatedBandwidth *model = [self.list objectOrNilAtIndex:indexPath.row];
    kWeakSelf(self);
    [TheRedemptionViewController alertController:self infoDelegate:model withWallet:self.wallet sureBlock:^(BOOL success) {
        if (success) {
            [weakself loadMore:NO];
        }
    }];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath  {
    if (tableView.isEditing) {
        [self.chooseArr removeObject:indexPath];
        self.bottomView.allBtn.selected = self.chooseArr.count==self.list.count;
        self.bottomView.deleteBtn.enabled =self.chooseArr.count;
    }
}
#pragma mark - getter
- (BottomView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[BottomView alloc] initWithFrame:CGRectMake(0, self.view.bottom, self.view.width, kTabBarHeight)];
        _bottomView.backgroundColor = kColorMain;
        [_bottomView.deleteBtn addTarget:self action:@selector(deleteData) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.allBtn addTarget:self action:@selector(tapAllBtn:) forControlEvents:UIControlEventTouchUpInside];
        _bottomView.deleteBtn.enabled = NO;
    }
    return _bottomView;
}

- (EOSService*)eosService{
    if (!_eosService) {
        _eosService = [EOSService new];
    }
    return _eosService;
}
- (NSMutableArray<EOSAccountDelegatedBandwidth*>*)list{
    if (!_list) {
        _list = [NSMutableArray array];
    }
    return _list;
}

- (NSMutableArray*)chooseArr{
    if (!_chooseArr) {
        _chooseArr = [NSMutableArray array];
    }
    return _chooseArr;
}
@end
